<?php

namespace catchAdmin\storehouse\controller;

use catchAdmin\product\model\Pack;
use catchAdmin\product\model\Product;
use catchAdmin\stock\model\Stock;
use catchAdmin\storehouse\model\Tray;
use catchAdmin\stock\model\WarehouseConfig;
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\storehouse\model\WarehousingSon as WarehousingSonModel;
use Picqer\Barcode\BarcodeGenerator;
use Picqer\Barcode\BarcodeGeneratorPNG;
use think\db\exception\DbException;
use think\Exception;
use think\exception\HttpException;
use think\Response;
use catcher\CatchAuth;
use think\facade\Db;

class WarehousingSon extends CatchController
{

    protected $warehousingSonModel;
    protected $productModel;

    /**
     *
     * @time 2022/01/19 11:52
     * @param WarehousingSonModel $warehousingSonModel
     * @return mixed
     */
    public function __construct(WarehousingSonModel $warehousingSonModel, Product $productModel)
    {
        $this->warehousingSonModel = $warehousingSonModel;
        $this->productModel = $productModel;
    }

    /**
     * 入库商品明细列表
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        $list = $this->warehousingSonModel->getList($user['tenant_id']);
        foreach ($list as $k => $v) {
            $list[$k]['tip'] = $k + 1;
        }
        return CatchResponse::paginate($list);
    }

    /**
     * 入库商品添加
     * @time 2022/01/19 11:52
     * @param Request $request
     */
    public function create(CatchAuth $auth, Request $request)
    {
        //return json(111);

        $params = $request->filterEmptyField()->post();
        $params["warehousing_son_config_attribute"]="1,9545";
        $user = $auth->user();
        if (empty($params['batch_number'])) {
            $params['batch_number'] = 'p' . date('YmdHis') . rand(1000, 9999);
        }

        //$params['pallet_no'] = 'P' . date('YmdHis') . rand(1000, 9999);
        //$params['goods_id']=  $this->productModel->where('goods_name',$params['goods_name'])->value('goods_id');
        $params['tenant_id'] = $user['tenant_id'];
        $params['warehousing_son_id'] = $user['tenant_id'] . date('YmdHis') . rand(1000, 9999);
        $params['enter_type'] = 1;
        $params['type'] = 'add';
        $params = $this->goods_info($params);

//        return CatchResponse::fail($params);

        if ($params['code'] === 0) {
            return CatchResponse::fail($params['msg']);
        } else {
            $specification = Db::table('db_packing')->field('packing_num,unit_name,layup_num')->where('packing_id', $params['data']['packing_id'])->find();


            //return json($specification);

            //xyuy ---start--- 货物分配库位，托盘
            $trayBoxNum = (new Pack)->getTrayBoxNum($params['data']['number'], $params['data']['packing_id']);
            $params['data']['tray_number'] = $trayBoxNum['tray_num'];
            $params['data']['box_number'] = $trayBoxNum['box_num'];
            $params['data']['specification'] = $specification['packing_num'] . ' / ' . $specification['unit_name'] . " /" . $specification['layup_num'];

            //分配库位

//            $autoConversionParams = [
//                'tray_num'=>$trayBoxNum['tray_num'],
//                'box_num'=>$trayBoxNum['box_num'],
//                'packing_num'=>$specification['packing_num'],
//                'total_num'=>$params['data']['number'],
//                'warehousing_id'=>$params['data']['warehousing_id'],
//                'warehousing_son_id'=>$params['data']['warehousing_son_id'],
//                'batch_number'=>$params['data']['batch_number'],
//                'packing_layup_num'=>$specification['layup_num'],
//                'packing_id'=>$params['data']['packing_id']
////                'packing_box_num'
//            ];

//            $res = $this->warehousingSonModel->autoConversionByGidNum($params['data']['goods_id'],$autoConversionParams);
            //判断是否是专属商品（专属商品，只能放置在隔离区，暂放区）
            //普通商品，只能繁放在（存储，赞放区）

            //根据需要的托盘数量（一库一托盘）拉取前面的 几个库位

            //拿到库位， insertAll写入数据（托盘表，入库产品表）

            // return json($res);

            Db::startTrans();
            try {
                /*
                //1。分配-1
                $this->warehousingSonModel->autoConversionByGidNum($params['data']['goods_id'],$autoConversionParams);
              */

                //2。更新子订单表
                $pk = $this->warehousingSonModel->storeBy($params['data']);

                Db::commit();
                return CatchResponse::success($pk);
            } catch (\Exception $exception) {
                Db::rollback();
                return CatchResponse::fail('系统自动分配库位失败' . $exception->getMessage());
            }


            //xyuy ---end---

        }
    }


    /**
     * 创建栈板号
     * @time 2022/01/19 11:52
     * goods_id
     * warehousing_son_id
     * warehousing_id
     * sn_list
     * @param Request $request
     */
    public function createPalletNo(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $params = $request->filterEmptyField()->post();
        //return CatchResponse::success($params);
        $params['config_id'] = '20250708142453';
        $params['tenant_id'] = $user['tenant_id'];
        $warehousingInfo = Db::table('db_warehousing')->where([
            'warehousing_id' => $params['warehousing_id']
        ])->find();
        if (empty($warehousingInfo)) {
            return CatchResponse::fail('没有找到主单数据！');
        }
        if ($warehousingInfo['status'] === 1) {
            return CatchResponse::fail('主单已经全部入库，请勿操作！');
        }
        $warehousingSonInfo = Db::table('db_warehousing_son')
            ->where([
                'warehousing_id' => $params['warehousing_id'],
                'warehousing_son_id' => $params['warehousing_son_id'],
                'goods_id' => $params['goods_id'],
                'deleted_at' => 0
            ])->find();
        if (empty($warehousingSonInfo)) {
            return CatchResponse::fail('没有找到明细单！');
        }
        $commodity = Db::table('db_product')
            ->where([
                'goods_id' => $params['goods_id'],
                'deleted_at' => 0
            ])->find();
        if (empty($commodity)) {
            return CatchResponse::fail('商品不存在！');
        }
        $snInfo =[];
        if (!empty($params['pallet_no'])) {
            $snInfo = Db::table('db_warehousing_sn')->where([
                'warehousing_id' => $params['warehousing_id'],
                'warehousing_son_id' => $params['warehousing_son_id'],
                'goods_id' => $params['goods_id'],
                'pallet_no' => $params['pallet_no'],
            ])->find();
            if(empty($snInfo))
                return CatchResponse::fail('未找到栈板号相关数据!');
        }else{
            $params['pallet_no'] = 'P' . date('YmdHis') . rand(1000, 9999);
        }
        $snList = [];
        if (!empty($params['sn_list'])) {
            $snList = explode(',', $params['sn_list']);
        } else {
            return CatchResponse::fail('请填写SN码！');
        }
        $SnCount = Db::table('db_warehousing_sn')->where([
            'warehousing_id' => $params['warehousing_id'],
            'warehousing_son_id' => $params['warehousing_son_id'],
            'goods_id' => $params['goods_id'],
            'deleted_at' => 0
        ])->where('pallet_no','<>',$params['pallet_no'])->count();
        $SnCount = count($snList) + $SnCount;
        if ($SnCount > $warehousingSonInfo['number']) {
            return CatchResponse::fail('本次录入的SN码加上已录入的超出了明细单商品数量！');
        }
        $snData = [];
        foreach ($snList as $sVal) {
            if (!empty(DB::name('db_warehousing_sn')
                ->where([
                    'deleted_at' => 0,
                    'sn' => $sVal,
                    'creator_id' => $user['id']
                ])->where('pallet_no','<>',$params['pallet_no'])->find())) {
                return CatchResponse::fail('sn码：' . $sVal . '已存在，请重新输入！');
            }
            $snData[] = [
                'warehousing_id' => $params['warehousing_id'],
                'warehousing_son_id' => $params['warehousing_son_id'],
                'config_id' => $params['config_id'],
                'number' => 1,
                'sn' => $sVal,
                'creator_id' => $user['id'],
                'created_at' => time(),
                'pallet_no' => $params['pallet_no'],
                'tenant_id' => $user['tenant_id'],
                'goods_id' => $params['goods_id'],
            ];
        }

        Db::startTrans();
        try {
            if (!empty($snInfo)) {
                Db::table('db_tray')->where([
                    'warehousing_id' => $params['warehousing_id'],
                    'warehousing_son_id' => $params['warehousing_son_id'],
                    'tray_id' => $snInfo['tray_id'],
                ])->delete();
                Db::table('db_warehousing_product')->where([
                    'warehousing_id' => $params['warehousing_id'],
                    'warehousing_son_id' => $params['warehousing_son_id'],
                    'goods_id' => $params['goods_id'],
                    'id' => $snInfo['warehousing_product_id'],
                ])->delete();
                Db::table('db_warehousing_sn')->where([
                    'warehousing_id' => $params['warehousing_id'],
                    'warehousing_son_id' => $params['warehousing_son_id'],
                    'goods_id' => $params['goods_id'],
                    'pallet_no' => $params['pallet_no'],
                ])->delete();
            }
            $res = self::createTray($params, $commodity, $warehousingSonInfo, $user, $snList);
            foreach ($snData as &$v) {
                $v['tray_id'] = $res['trayId'];
                $v['warehousing_product_id'] = $res['productId'];
            }
            DB::name('db_warehousing_sn')->insertAll($snData);
            // 使用picqer库生成
//            $generator = new BarcodeGeneratorPNG();
//            $barcode = $generator->getBarcode($params['pallet_no'], BarcodeGenerator::TYPE_CODE_128);
//            $palletNoImg = 'data:image/png;base64,' . base64_encode($barcode);
            Db::commit();
            return CatchResponse::success(['pallet_no' => $params['pallet_no']]);
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail($exception->getMessage());
        }
    }


    public static function createTray($params, $commodity, $warehousing_son, $user, $snList): array
    {
        $data = [];
        $product = [];
        $box_number = 0;
        $user_co_code = Db::table('users')->where('id', $user['tenant_id'])->value('co_code');
        $data['tray_id'] = $user_co_code . 'T' . date('YmdHis') . rand(1000000, 9999999);
        $data['warehousing_id'] = $params['warehousing_id'];
        $data['warehousing_son_id'] = $params['warehousing_son_id'];
        $data['config_id'] = $params['config_id'];
        $data['tenant_id'] = $user['tenant_id'];
        $data['status'] = '0';
        $data['LOT1'] = $v['LOT1'] ?? '';
        $data['LOT2'] = $v['LOT2'] ?? '';
        $data['LOT3'] = $v['LOT3'] ?? '';
        $data['goods_status'] = 'Good';
        $data['created_at'] = time();
        $data['box_number'] = count($snList);
        $box_number += count($snList);
        $data['number'] = count($snList);
        $data['batch_number'] = $warehousing_son['batch_number'];
        $data['creator_id'] = $user['id'];
        //product
        $product['warehousing_id'] = $params['warehousing_id'];
        $product['warehousing_son_id'] = $warehousing_son['warehousing_son_id'];
        $product['goods_name'] = $warehousing_son['goods_name'];
        $product['goods_id'] = $commodity['goods_id'];
        $product['goods_Cname'] = $commodity['goods_Cname'];
        $product['goods_Ename'] = $commodity['goods_Ename'];
        $product['manufacturer_id'] = $commodity['manufacturer_id'];
        $product['manufacturer_name'] = Db::table('db_manufacturer')->where('manufacturer_id', $commodity['manufacturer_id'])->value('manufacturer_name');
        $product['supplier_id'] = $commodity['supplier_id'];
        $product['supplier_name'] = Db::table('db_supplier')->where('supplier_id', $commodity['supplier_id'])->value('supplier_name');
        $product['packing_id'] = $warehousing_son['packing_id'];
        $product['p_barcode'] = $warehousing_son['packing_id'];
        $packing = Db::table('db_packing')->where('packing_id', $warehousing_son['packing_id'])->find();
        $product['packing_num'] = $packing['packing_num'];
        $product['unit_name'] = $packing['unit_name'];
        $product['number'] = count($snList);
        $product['box_number'] = count($snList);
        $product['created_at'] = time();
        $product['tenant_id'] = $user['tenant_id'];
        $product['creator_id'] = $user['id'];
        $product['tray_id'] = $data['tray_id'];
        $product['specification'] = $packing['packing_num'] . ' / ' . $packing['unit_name'] . ' /' . $packing['layup_num'];
        $product['LOT1'] = $data['LOT1'];
        $product['LOT2'] = $data['LOT2'];
        $product['LOT3'] = $data['LOT3'];
        //重新写入编辑后的数据
        Db::table('db_tray')->insert($data);
        $productId = Db::table('db_warehousing_product')->insert($product, true);
        $arr = ['tray_number' => 1, 'box_number' => count($snList)];
        Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing_son_id'])->update($arr);
        return ['trayId' => $data['tray_id'], 'productId' => $productId];
    }


    public function getPalletNoList(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $params = $request->filterEmptyField()->post();
        $palletNoList = Db::table('db_warehousing_sn')->field('
        pallet_no,
        sn
        ')->where([
            'warehousing_id' => $params['warehousing_id'],
            'warehousing_son_id' => $params['warehousing_son_id'],
            'goods_id' => $params['goods_id'],
            'deleted_at' => 0
        ])->select()->toArray();
        $list = [];
        if (!empty($palletNoList)) {
            $pList = array_values(array_unique(array_column($palletNoList, 'pallet_no')));
            foreach ($pList as $pVal) {
                $snList = [];
                foreach ($palletNoList as $val) {
                    if ($pVal == $val['pallet_no']) {
                        $snList[] = $val['sn'];
                    }
                }
                $list[$pVal] = $snList;
            }
        }
        return CatchResponse::success($list);
    }

    public function delPalletNo(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $params = $request->filterEmptyField()->post();
        $snInfo = Db::table('db_warehousing_sn')->where([
            'warehousing_id' => $params['warehousing_id'],
            'warehousing_son_id' => $params['warehousing_son_id'],
            'goods_id' => $params['goods_id'],
            'pallet_no' => $params['pallet_no'],
        ])->find();

        if (empty($snInfo))
            return CatchResponse::fail('删除失败');
        Db::startTrans();
        try {

            Db::table('db_tray')->where([
                'warehousing_id' => $params['warehousing_id'],
                'warehousing_son_id' => $params['warehousing_son_id'],
                'tray_id' => $snInfo['tray_id'],
            ])->delete();

            $bool =Db::table('db_warehousing_product')->where([
                'warehousing_id' => $params['warehousing_id'],
                'warehousing_son_id' => $params['warehousing_son_id'],
                'goods_id' => $params['goods_id'],
                'id' => $snInfo['warehousing_product_id'],
            ])->delete();
            Db::table('db_warehousing_sn')->where([
                'warehousing_id' => $params['warehousing_id'],
                'warehousing_son_id' => $params['warehousing_son_id'],
                'goods_id' => $params['goods_id'],
                'pallet_no' => $params['pallet_no'],
            ])->delete();
            Db::commit();
            return CatchResponse::success();
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail($exception->getMessage());
        }
    }

    public function is_stock($type, $warehousing_id, $warehousing_son_id, $new_num)
    {
        if ($type == 'add') {
            $warehousing = Db::table('db_warehousing')->where('warehousing_id', $warehousing_id)->find();
            $warehousing_son_num = Db::table('db_warehousing_son')->where('warehousing_id', $warehousing_id)->sum('number');
            $surplus = $warehousing['goods_number'] - intval($warehousing_son_num);
            if (intval($new_num) > $surplus) {
                return false;
            } else {
                return true;
            }
        } else if ($type == 'edit') {
            $warehousing = Db::table('db_warehousing')->where('warehousing_id', $warehousing_id)->find();
            $where = [];
            $where[] = ['warehousing_id', '=', $warehousing_id];
            $where[] = ['warehousing_son_id', '<>', $warehousing_son_id];
            $warehousing_son_num = Db::table('db_warehousing_son')->where($where)->sum('number');
            $surplus = $warehousing['goods_number'] - intval($warehousing_son_num);
            if (intval($new_num) > $surplus) {
                return false;
            } else {
                return true;
            }
        }
    }

    /**
     * 入库商品添加
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return Response
     */
    public function createAdd(CatchAuth $auth, Request $request)
    {
        $params = $request->filterEmptyField()->post();

        $user = $auth->user();
        // list choice warehousing
        $result = $this->is_stock('add', $params['warehousing']['warehousing_id'], '', $params['warehousing']['number']);
        if (!$result) {
            return CatchResponse::fail('超过入库单最大数量！');
        }
        //库位是否被占
//        $config_ids = Db::table('db_warehouse_config')->where('name','in',$params['choice'])->column('config_id');
//        $if_tray=Db::table('db_tray')->where([['status','=',0],['config_id','in',$config_ids],['deleted_at','=',0]])->find();
//        $if_stock=Db::table('db_stock')->where([['status','<>',1],['config_id','in',$config_ids],['deleted_at','=',0]])->find();
//        if($if_tray||$if_stock){
//            return CatchResponse::fail('库位被占用！');
//        }
        Db::startTrans();
        try {
            $warehousing_son = [];
            $warehousing_son['warehousing_id'] = $params['warehousing']['warehousing_id'];
            $warehousing_son['warehousing_son_id'] = $user['tenant_id'] . date('YmdHis') . rand(1000, 9999);
            $warehousing_son['batch_number'] = empty($params['warehousing']['batch_number']) ? 'p' . date('YmdHis') . rand(1000, 9999) : $params['warehousing']['batch_number'];
            $warehousing_son['number'] = $params['warehousing']['number'];
            $warehousing_son['box_number'] = $params['warehousing']['box_number'];
            $warehousing_son['tray_number'] = $params['warehousing']['tray_number'];
            $warehousing_son['created_at'] = time();
            $warehousing_son['tenant_id'] = $user['tenant_id'];
            $warehousing_son['creator_id'] = $user['id'];
            if (!empty($params['enter_type'])) {
                $warehousing_son['enter_type'] = $params['enter_type'];
            }
            Db::table('db_warehousing_son')->insert($warehousing_son);
            foreach ($params['list'] as $key => $vo) {
                $config = Db::table('db_warehouse_config')->where('name', $params['choice'][$key])->find();
                if (empty($config)) {
                    Db::rollback();
                    return CatchResponse::fail('库位不存在！');
                }
                //托盘码是否存在，不存在自动生成
                if (!empty($vo['tray_id'])) {
                    $tray = Db::table('db_tray')->where('tray_id', $vo['tray_id'])->find();
                    if ($tray) {
                        Db::rollback();
                        return CatchResponse::fail('托盘码已存在！');
                    }
                } else {
                    $vo['tray_id'] = 't' . date('YmdHis') . rand(1000, 9999) . $key;
                }
                $tray = [];
                $tray['warehousing_id'] = $params['warehousing']['warehousing_id'];
                $tray['warehousing_son_id'] = $warehousing_son['warehousing_son_id'];
                $tray['tray_id'] = $vo['tray_id'];
                $tray['config_id'] = Db::table('db_warehouse_config')->where('name', $params['choice'][$key])->value('config_id');
                $tray['number'] = $vo['number'];
                $tray['box_number'] = $vo['box_number'];
                $tray['goods_status'] = empty($vo['goods_status']) ? 'Good' : $vo['goods_status'];
                $tray['created_at'] = time();
                $tray['tenant_id'] = $user['tenant_id'];
                $tray['creator_id'] = $user['id'];
                $t_id = Db::table('db_tray')->insertGetId($tray);
                foreach ($vo['products'] as $k => $v) {
                    $product = [];
                    $product['t_id'] = $t_id;
                    $product['warehousing_id'] = $params['warehousing']['warehousing_id'];
                    $product['warehousing_son_id'] = $warehousing_son['warehousing_son_id'];
                    $product['goods_name'] = $v['goods_name'];
                    $commodity = Db::table('db_product')->where('goods_name', $product['goods_name'])->find();
                    if (empty($commodity)) {
                        Db::rollback();
                        return CatchResponse::fail('商品料号不存在！');
                    }
                    $product['goods_id'] = $commodity['goods_id'];
                    $product['goods_Cname'] = $commodity['goods_Cname'];
                    $product['goods_Ename'] = $commodity['goods_Ename'];
                    $product['manufacturer_id'] = $commodity['manufacturer_id'];
                    $product['manufacturer_name'] = Db::table('db_manufacturer')->where('manufacturer_id', $product['manufacturer_id'])->value('manufacturer_name');
                    $product['supplier_id'] = $commodity['supplier_id'];
                    $product['supplier_name'] = Db::table('db_supplier')->where('supplier_id', $product['supplier_id'])->value('supplier_name');
                    $product['packing_id'] = $v['packing_id'];
                    $product['p_barcode'] = $v['packing_id'];
                    $packing = Db::table('db_packing')->where('packing_id', $v['packing_id'])->find();
//                    if(empty($packing)){
//                        Db::rollback();
//                        return CatchResponse::fail('包装错误！');
//                    }
                    $product['packing_num'] = $packing['packing_num'];
                    $product['unit_name'] = $packing['unit_name'];
                    $product['number'] = $v['number'];
                    $product['box_number'] = $v['box_number'];
                    $product['created_at'] = time();
                    $product['tenant_id'] = $user['tenant_id'];
                    $product['creator_id'] = $user['id'];
                    $product['tray_id'] = $vo['tray_id'];
                    $product['specification'] = $packing['packing_num'] . ' / ' . $packing['unit_name'];
                    Db::table('db_warehousing_product')->insert($product);
                }
            }
            Db::commit();
            return CatchResponse::success('', '添加成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('添加失败');
        }
    }

    /**
     * 入库查询
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return Response
     */
    public function createEdit(CatchAuth $auth, Request $request)
    {
        $params = $request->filterEmptyField()->post();
        $user = $auth->user();
        $where = [];
        $where[] = ['deleted_at', '=', 0];
        $where[] = ['warehousing_id', '=', $params['warehousing']['warehousing_id']];
        $where[] = ['warehousing_son_id', '=', $params['warehousing']['warehousing_son_id']];
        $warehousing_son = Db::table('db_warehousing_son')->where($where)->find();
        if (empty($warehousing_son)) {
            return CatchResponse::fail('单号错误！');
        }
        if ($warehousing_son['status'] == 1) {
            return CatchResponse::fail('该订单已入库！');
        }
        $result = $this->is_stock('edit', $params['warehousing']['warehousing_id'], $params['warehousing']['warehousing_son_id'], $params['warehousing']['number']);
        if (!$result) {
            return CatchResponse::fail('超过入库单最大数量！');
        }
        // list choice warehousing
        Db::startTrans();
        try {
            $warehousing_son = [];
            $warehousing_son['batch_number'] = $params['warehousing']['batch_number'];
            $warehousing_son['number'] = $params['warehousing']['number'];
            $warehousing_son['box_number'] = empty($params['warehousing']['batch_number']) ? 'p' . date('YmdHis') . rand(1000, 9999) : $params['warehousing']['batch_number'];//$params['warehousing']['box_number'];
            $warehousing_son['tray_number'] = $params['warehousing']['tray_number'];
            $warehousing_son['updated_at'] = time();
            Db::table('db_warehousing_son')->where($where)->update($warehousing_son);
            Db::table('db_tray')->where(['warehousing_son_id' => $params['warehousing']['warehousing_son_id']])->delete();
            Db::table('db_warehousing_product')->where(['warehousing_son_id' => $params['warehousing']['warehousing_son_id']])->delete();

            foreach ($params['list'] as $key => $vo) {
                $config = Db::table('db_warehouse_config')->where('name', $params['choice'][$key])->find();
                if (empty($config)) {
                    Db::rollback();
                    return CatchResponse::fail('库位不存在！');
                }
                //托盘码是否存在，不存在自动生成
                if (!empty($vo['tray_id'])) {
                    $tray = Db::table('db_tray')->where('tray_id', $vo['tray_id'])->find();
                    if ($tray) {
                        Db::rollback();
                        return CatchResponse::fail('托盘码已存在！');
                    }
                } else {
                    $vo['tray_id'] = 't' . date('YmdHis') . rand(1000, 9999) . $key;
                }
//                $tray = Db::table('db_tray')->where('tray_id',$vo['tray_id'])->find();
//                if($tray){
//                    Db::rollback();
//                    return CatchResponse::fail('托盘码已存在！');
//                }
                $tray = [];
                $tray['warehousing_id'] = $params['warehousing']['warehousing_id'];
                $tray['warehousing_son_id'] = $params['warehousing']['warehousing_son_id'];
                $tray['tray_id'] = $vo['tray_id'];
                $tray['config_id'] = $tray['config_id'] = Db::table('db_warehouse_config')->where('name', $params['choice'][$key])->value('config_id');
                $tray['number'] = $vo['number'];
                $tray['box_number'] = $vo['box_number'];
                $tray['goods_status'] = empty($vo['goods_status']) ? 'Good' : $vo['goods_status'];//$vo['goods_status'];
                $tray['created_at'] = time();
                $tray['tenant_id'] = $user['tenant_id'];
                $tray['creator_id'] = $user['id'];
                Db::table('db_tray')->insert($tray);
                foreach ($vo['products'] as $k => $v) {
                    $product = [];
                    $product['warehousing_id'] = $params['warehousing']['warehousing_id'];
                    $product['warehousing_son_id'] = $params['warehousing']['warehousing_son_id'];
                    $product['goods_name'] = $v['goods_name'];
                    $commodity = Db::table('db_product')->where('goods_name', $product['goods_name'])->find();
                    if (empty($commodity)) {
                        Db::rollback();
                        return CatchResponse::fail('商品料号不存在！');
                    }
                    $product['goods_id'] = $commodity['goods_id'];
                    $product['goods_Cname'] = $commodity['goods_Cname'];
                    $product['goods_Ename'] = $commodity['goods_Ename'];
                    $product['manufacturer_id'] = $commodity['manufacturer_id'];
                    $product['manufacturer_name'] = Db::table('db_manufacturer')->where('manufacturer_id', $product['manufacturer_id'])->value('manufacturer_name');
                    $product['supplier_id'] = $commodity['supplier_id'];
                    $product['supplier_name'] = Db::table('db_supplier')->where('supplier_id', $product['supplier_id'])->value('supplier_name');
                    $product['packing_id'] = $v['packing_id'];//$commodity['packing_id'];
                    $product['p_barcode'] = $v['packing_id'];//$commodity['packing_id'];
                    $packing = Db::table('db_packing')->where('packing_id', $v['packing_id'])->find();
//                    if(empty($packing)){
//                        Db::rollback();
//                        return CatchResponse::fail('包装错误！');
//                    }
                    $product['packing_num'] = $packing['packing_num'];
                    $product['unit_name'] = $packing['unit_name'];
                    $product['number'] = $v['number'];
                    $product['box_number'] = $v['box_number'];
                    $product['created_at'] = time();
                    $product['tenant_id'] = $user['tenant_id'];
                    $product['creator_id'] = $user['id'];
                    $product['tray_id'] = $vo['tray_id'];
                    $product['specification'] = $packing['packing_num'] . ' / ' . $packing['unit_name'];
                    Db::table('db_warehousing_product')->insert($product);
                }
            }
            Db::commit();
            return CatchResponse::success('', '修改成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('修改失败');
        }
    }

    /**
     * 入库查询
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return Response
     */
    public function getCreate(CatchAuth $auth, Request $request)
    {
        $warehousing_son_id = $request->post('warehousing_son_id');
        $user = $auth->user();
        $data = [];
        $warehousing_son_info = Db::table('db_warehousing_son')->field('warehousing_id,warehousing_son_id,batch_number,number,box_number,tray_number')->where('warehousing_son_id', $warehousing_son_id)->find();
        if (empty($warehousing_son_info)) {
            return CatchResponse::fail('单号错误！');
        }
        $data['warehousing'] = $warehousing_son_info;
        $choice = Db::table('db_tray')->where(['deleted_at' => 0, 'warehousing_son_id' => $warehousing_son_id])->column('config_id');
        $data['choice'] = $choice;
        $list = Db::table('db_tray')->field('tray_id,number,box_number,goods_status')->where(['deleted_at' => 0, 'warehousing_son_id' => $warehousing_son_id])->select()->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['products'] = Db::table('db_warehousing_product')->field('goods_name,number,box_number,packing_id')->where(['deleted_at' => 0, 'warehousing_son_id' => $warehousing_son_id, 'tray_id' => $v['tray_id']])->select();
        }
        $data['list'] = $list;
        return CatchResponse::success($data, '查询成功');
    }

    /**
     * 子单删除
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return Response
     */
    public function createDel(CatchAuth $auth, Request $request)
    {
        $warehousing_son_id = $request->post('warehousing_son_id');
        $warehousing_son_id = is_array($warehousing_son_id) ? $warehousing_son_id : [$warehousing_son_id];

        $warehousingSonModel = new WarehousingSonModel;
        $trayModel = new Tray;

        $warehousing_son = $warehousingSonModel->where('warehousing_son_id', 'in', $warehousing_son_id)->select()->toArray();

        foreach ($warehousing_son as $value) {
            if ($value['status'] != 0) {
                return CatchResponse::fail('该订单商品已入库，请确认！');
            }
        }

        Db::startTrans();
        try {
            Db::table('db_warehousing_son')->where('warehousing_son_id', 'in', $warehousing_son_id)->delete();
            Db::table('db_tray')->where('warehousing_son_id', 'in', $warehousing_son_id)->delete();
            Db::table('db_warehousing_product')->where('warehousing_son_id', 'in', $warehousing_son_id)->delete();
            Db::table('db_warehousing_sn')->where('warehousing_son_id', 'in', $warehousing_son_id)->delete();
            //Db::rollback();
            Db::commit();
            return CatchResponse::success('', '删除成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('删除失败');
        }
    }

    /**
     * 子单删除
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return Response
     */
    public function configDel(CatchAuth $auth, Request $request)
    {
        $params = $request->filterEmptyField()->post();
        $user = $auth->user();
        $where = [];
        $where[] = ['id', '=', $params['id']];
//        $where[] = ['config_id','=',$params['config_id']];
        $where[] = ['warehousing_son_id', '=', $params['warehousing_son_id']];
        $tray = Db::table('db_tray')->where($where)->find();
        if (empty($tray)) {
            return CatchResponse::fail('单号库位id错误');
        }
        if ($tray['status'] == 1) {
            return CatchResponse::fail('该库位商品已入库，无法删除');
        }

        $tray_surplus_counts = Db::table('db_tray')->where([
            ['deleted_at', '=', 0],
            ['warehousing_son_id', '=', $params['warehousing_son_id']]
        ])->count();

        Db::startTrans();
        try {
            Db::table('db_tray')->where($where)->delete();
            Db::table('db_warehousing_product')->where(['warehousing_son_id' => $params['warehousing_son_id'], 'tray_id' => $tray['tray_id']])->delete();

//            之前的Bug不需要更新子表的数量
//            Db::table('db_warehousing_son')->where('warehousing_son_id',$params['warehousing_son_id'])->dec('number', $tray['number'])->update();
            $tray_surplus_counts = Db::table('db_tray')->where([
                ['deleted_at', '=', 0],
                ['warehousing_son_id', '=', $params['warehousing_son_id']]
            ])->count();

            if (0 == $tray_surplus_counts) {
                //重新更新明细表
                $warehousing_son = Db::table('db_warehousing_son')->field('number,packing_id')->where('warehousing_son_id', $params['warehousing_son_id'])->find();
                $trayBoxNum = (new Pack)->getTrayBoxNum($warehousing_son['number'], $warehousing_son['packing_id']);
                Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing_son_id'])->update([
                    'tray_number' => $trayBoxNum['tray_num'],
                    'box_number' => $trayBoxNum['box_num']
                ]);
            } else {
                Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing_son_id'])->dec('box_number', $tray['box_number'])->update();
                Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing_son_id'])->dec('tray_number')->update();
            }
            Db::table('db_warehousing_sn')->where([
                'warehousing_son_id' => $params['warehousing_son_id'],
                'tray_id' => $tray['tray_id']
            ])->delete();
            Db::commit();
            return CatchResponse::success('', '删除成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('删除失败');
        }
    }

    /**
     * 订单入库
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return Response
     */
    public function goStockAll(CatchAuth $auth, Request $request)
    {
//        return false;

        $user = $auth->user();
        $warehousing_id = $request->post('warehousing_id');
        $warehousing = Db::table('db_warehousing')->where('warehousing_id', $warehousing_id)->find();
        if (empty($warehousing)) {
            return CatchResponse::fail('单号错误！');
        }
        $number_count = Db::table('db_warehousing_son')->where(['deleted_at' => 0, 'warehousing_id' => $warehousing_id])->sum('number');//子单总数
        $warehousing_son = Db::table('db_warehousing_son')
//            ->where(['status'=>0,'deleted_at'=>0,'warehousing_id'=>$warehousing_id])
            ->where([
                ['status', '<>', 1],
                ['deleted_at', '=', 0],
                ['warehousing_id', '=', $warehousing_id]
            ])
            ->select()->toArray();

        if ($warehousing['goods_number'] != $number_count) {
            return CatchResponse::fail("入库订单数量不一致，目标{$warehousing['goods_number']}，实际明细总和{$number_count}");
        }

        foreach ($warehousing_son as $value) {
            $tray_list = Db::table('db_tray')->where([
                ['deleted_at', '=', 0,],
                ['warehousing_son_id', '=', $value['warehousing_son_id']]
            ])->select()->toArray();

            if (empty($tray_list)) {
                return CatchResponse::fail('明细单请先选择库位');
            }
        }

        Db::startTrans();
        try {

            if ($number_count >= $warehousing['goods_number']) {
                $data = [];
                $data['actual_number'] = $number_count;
                $data['status'] = 1;
                Db::table('db_warehousing')->where('warehousing_id', $warehousing_id)->update($data);
            } else if ($number_count > 0 && $number_count < $warehousing['goods_number']) {
                $data = [];
                $data['actual_number'] = $number_count;
                $data['status'] = 2;
                Db::table('db_warehousing')->where('warehousing_id', $warehousing_id)->update($data);
            }

            foreach ($warehousing_son as $key => $vo) {
                if ($vo['status'] != 1 && $vo['number'] > 0) {
                    //db_warehousing_son db_tray db_warehousing_product db_stock
                    $data = [];
                    $data['status'] = 1;
                    $data['actual_number'] = $vo['number'];
                    //子单入库
                    Db::table('db_warehousing_son')->where('warehousing_son_id', $vo['warehousing_son_id'])->update($data);
                    $tray = Db::table('db_tray')->where('deleted_at', 0)->where('warehousing_son_id', $vo['warehousing_son_id'])->select()->toArray();
                    foreach ($tray as $k => $v) {
                        if ($v['status'] == 0) {
                            Db::table('db_tray')->where('id', $v['id'])->update(['status' => 1, 'updated_at' => time()]);
                            $products = Db::table('db_warehousing_product')->where(['warehousing_son_id' => $vo['warehousing_son_id'], 'tray_id' => $v['tray_id']])->select()->toArray();
                            foreach ($products as $h => $j) {
                                if ($j['status'] == 0) {
                                    Db::table('db_warehousing_product')->where('id', $j['id'])->update(['status' => 1]);
                                    //stock
                                    $data = [];

                                    $user_co_code = Db::table('users')->where('id', $user['tenant_id'])->value('co_code');
//                                    $data['stock_id']=date('YmdHis').mt_rand(1000,9999);
                                    $data['stock_id'] = $user_co_code . date('YmdHis') . mt_rand(1000, 9999);
                                    $data['warehousing_id'] = $warehousing_id;
                                    $data['warehousing_son_id'] = $vo['warehousing_son_id'];
                                    $data['tray_id'] = $v['tray_id'];
                                    $data['config_id'] = $v['config_id'];
                                    $data['project_id'] = $warehousing['project_id'];
                                    $data['project_client'] = $warehousing['project_client'];
                                    $data['number'] = $j['number'];
                                    $data['tray_number'] = 1;
                                    $data['box_number'] = $j['box_number'];
                                    $data['goods_id'] = $j['goods_id'];
                                    $data['goods_name'] = $j['goods_name'];
                                    $data['goods_Cname'] = $j['goods_Cname'];
                                    $data['goods_Ename'] = $j['goods_Ename'];
                                    $data['supplier_id'] = $j['supplier_id'];
                                    $data['supplier_name'] = $j['supplier_name'];
                                    $data['manufacturer_id'] = $j['manufacturer_id'];
                                    $data['manufacturer_name'] = $j['manufacturer_name'];
                                    $data['packing_id'] = $j['packing_id'];
                                    $data['p_barcode'] = $j['p_barcode'];
                                    $data['packing_num'] = $j['packing_num'];
                                    $data['unit_name'] = $j['unit_name'];
                                    $data['created_at'] = time();
                                    $data['status'] = 0;
                                    $data['split_status'] = 0;
                                    $data['tenant_id'] = $user['tenant_id'];
                                    $data['creator_id'] = $user['id'];
                                    $data['batch_number'] = $vo['batch_number'];
                                    if ($v['goods_status'] == 'Good') {
                                        $data['Good_Qty'] = $data['number'];
                                    } else if ($v['goods_status'] == 'NG') {
                                        $data['NG_Qty'] = $data['number'];
                                    } else if ($v['goods_status'] == 'Hold') {
                                        $data['Hold_Qty'] = $data['number'];
                                    }
                                    $data['LOT1'] = $j['LOT1'];
                                    $data['LOT2'] = $j['LOT2'];
                                    $data['LOT3'] = $j['LOT3'];

                                    $parent_id = Db::table('db_warehouse_config')->where('config_id', $v['config_id'])->value('parent_id');
                                    $grand_parent_id = Db::table('db_warehouse_config')->where('id', $parent_id)->value('parent_id');
                                    $grand_parent = Db::table('db_warehouse_config')->where('id', $grand_parent_id)->find();
                                    $data['entrepot_name'] = $grand_parent['name'];
                                    $data['entrepot_id'] = $grand_parent['config_id'];
                                    Db::table('db_stock')->insert($data);

                                    //添加库存操作记录--start
                                    $inventoryOperationRecordModel = new \catchAdmin\storehouse\model\InventoryOperationRecord();
                                    //--记录托盘号，和库存编号
                                    $recordResult = (new InventoryOperationRecord($inventoryOperationRecordModel))
                                        ->write(InventoryOperationRecord::ORDER_TYPE_RK, $vo['warehousing_son_id'], $data);
                                    if (!$recordResult) {
                                        Db::rollback();
                                        throw new Exception('[入库]库存操作记录创建失败');
                                    }
                                    //添加库存操作记录--end
                                }
                            }


                        }
                    }
                    $snWhere = [
                        'warehousing_id' => $vo['warehousing_id'],
                        'warehousing_son_id' => $vo['warehousing_son_id'],
                        'goods_id' => $vo['goods_id'],
                        'deleted_at' => 0
                    ];
                    Db::table('db_warehousing_sn')->where($snWhere)
                        ->update([
                            'status' => 1,
                            'updated_at' => time()
                        ]);
                }
            }
            Db::commit();
            return CatchResponse::success('', '入库成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('入库失败' . $exception->getMessage());
        }
    }

    /**
     * 一键入库
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return Response
     */
    public function goStock(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $params = $request->filterEmptyField()->post();
        $trays = Db::table('db_tray')->where([['deleted_at', '=', 0], ['id', 'in', $params['ids']], ['status', '=', 0]])->select()->toArray();

        $tray_number = Db::table('db_tray')->where([['deleted_at', '=', 0], ['id', 'in', $params['ids']], ['status', '=', 0]])->sum('number');

        $warehousing = Db::table('db_warehousing')->where('warehousing_id', $params['warehousing_id'])->find();
        $warehousing_son = Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing_son_id'])->find();
        if (empty($trays)) {
            return CatchResponse::success('', '入库成功');
        }
//        //xyuy -- 判断入库数量是否等于订单数量
//        if($warehousing_son['number'] != $tray_number){
//            return CatchResponse::fail("入库订单数量不一致，目标{$warehousing_son['number']}，实际{$tray_number}");
//        }

        Db::startTrans();
        try {
            $up_number = $warehousing_son['actual_number'] + $tray_number;
            if ($warehousing_son['number'] == $up_number) {
                Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing_son_id'])->update(['actual_number' => $warehousing_son['number'], 'status' => 1]);
            } else {
                Db::table('db_warehousing_son')->where('warehousing_son_id', $params['warehousing_son_id'])->update(['actual_number' => $up_number, 'status' => 2]);
            }
            $up_number = $warehousing['actual_number'] + $tray_number;
            if ($warehousing['goods_number'] == $up_number) {
                Db::table('db_warehousing')->where('warehousing_id', $params['warehousing_id'])->update(['actual_number' => $warehousing['goods_number'], 'status' => 1]);
            } else {
                Db::table('db_warehousing')->where('warehousing_id', $params['warehousing_id'])->update(['actual_number' => $up_number, 'status' => 2]);
            }
            foreach ($trays as $k => $v) {
                if ($v['status'] == 0) {
                    Db::table('db_tray')->where('id', $v['id'])->update(['status' => 1, 'updated_at' => time()]);
                    $products = Db::table('db_warehousing_product')->where(['warehousing_son_id' => $params['warehousing_son_id'], 'tray_id' => $v['tray_id']])->select()->toArray();
                    foreach ($products as $h => $j) {
                        if ($j['status'] == 0) {
                            Db::table('db_warehousing_product')->where('id', $j['id'])->update(['status' => 1]);
                            //stock
                            $data = [];

                            $user_co_code = Db::table('users')->where('id', $user['tenant_id'])->value('co_code');
//                            $data['stock_id']=date('YmdHis').mt_rand(1000,9999);
                            $data['stock_id'] = $user_co_code . date('YmdHis') . mt_rand(1000, 9999);

                            $data['warehousing_id'] = $params['warehousing_id'];
                            $data['warehousing_son_id'] = $params['warehousing_son_id'];
                            $data['tray_id'] = $v['tray_id'];
                            $data['config_id'] = $v['config_id'];
                            $data['project_id'] = $warehousing['project_id'];
                            $data['project_client'] = $warehousing['project_client'];
                            $data['number'] = $j['number'];
                            $data['tray_number'] = 1;
                            $data['box_number'] = $j['box_number'];
                            $data['goods_id'] = $j['goods_id'];
                            $data['goods_name'] = $j['goods_name'];
                            $data['goods_Cname'] = $j['goods_Cname'];
                            $data['goods_Ename'] = $j['goods_Ename'];
                            $data['supplier_id'] = $j['supplier_id'];
                            $data['supplier_name'] = $j['supplier_name'];
                            $data['manufacturer_id'] = $j['manufacturer_id'];
                            $data['manufacturer_name'] = $j['manufacturer_name'];
                            $data['packing_id'] = $j['packing_id'];
                            $data['p_barcode'] = $j['p_barcode'];
                            $data['packing_num'] = $j['packing_num'];
                            $data['unit_name'] = $j['unit_name'];
                            $data['created_at'] = time();
                            $data['status'] = 0;
                            $data['split_status'] = 0;
                            $data['tenant_id'] = $user['tenant_id'];
                            $data['creator_id'] = $user['id'];
                            $data['batch_number'] = $warehousing_son['batch_number'];
                            if ($v['goods_status'] == 'Good') {
                                $data['Good_Qty'] = $data['number'];
                            } else if ($v['goods_status'] == 'NG') {
                                $data['NG_Qty'] = $data['number'];
                            } else if ($v['goods_status'] == 'Hold') {
                                $data['Hold_Qty'] = $data['number'];
                            }
                            $data['LOT1'] = $j['LOT1'];
                            $data['LOT2'] = $j['LOT2'];
                            $data['LOT3'] = $j['LOT3'];
                            $parent_id = Db::table('db_warehouse_config')->where('config_id', $v['config_id'])->value('parent_id');
                            $grand_parent_id = Db::table('db_warehouse_config')->where('id', $parent_id)->value('parent_id');
                            $grand_parent = Db::table('db_warehouse_config')->where('id', $grand_parent_id)->find();
                            $data['entrepot_name'] = $grand_parent['name'];
                            $data['entrepot_id'] = $grand_parent['config_id'];
                            Db::table('db_stock')->insert($data);


                            $snWhere = [
                                'warehousing_id' => $data['warehousing_id'],
                                'warehousing_son_id' => $data['warehousing_son_id'],
                                'goods_id' => $data['goods_id'],
                                'deleted_at' => 0
                            ];
                            Db::table('db_warehousing_sn')->where($snWhere)
                                ->update([
                                    'status' => 1,
                                    'updated_at' => time()
                                ]);

                            //添加库存操作记录--start
                            $inventoryOperationRecordModel = new \catchAdmin\storehouse\model\InventoryOperationRecord();
                            //添加库存ID 托盘ID
                            $recordResult = (new InventoryOperationRecord($inventoryOperationRecordModel))->write(InventoryOperationRecord::ORDER_TYPE_RK, $params['warehousing_son_id'], $data);
                            if (!$recordResult) {
                                Db::rollback();
                                throw new Exception('[入库]库存操作记录创建失败');
                            }
                            //添加库存操作记录--end
                        }
                    }
                }
            }
            Db::commit();
            return CatchResponse::success('', '入库成功');
        } catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('入库失败' . $exception->getMessage());
        }
    }

    /**
     *
     * @time 2022/01/19 11:52
     * @param $id
     * @return Response
     */
    public function read($id): Response
    {
        return CatchResponse::success($this->warehousingSonModel->findBy($id));
    }


    public function update(Request $request): Response
    {
        $params = $request->filterEmptyField()->post();
        $params['type'] = 'edit';
        $params['id'] = $params['id'];
        $params = $this->goods_info($params);
        if ($params['code'] === 0) {
            return CatchResponse::fail($params['msg']);
        } else {
            //$specification=Db::table('db_packing')->field('packing_num,unit_name')->where('packing_id',$params['data']['packing_id'])->find();
            //$params['data']['specification']=$specification['packing_num'].' / '.$specification['unit_name'];

            $specification = Db::table('db_packing')->field('packing_num,unit_name,layup_num')->where('packing_id', $params['data']['packing_id'])->find();
            //xyuy ---start--- 重新计算托盘数量
            $trayBoxNum = (new Pack)->getTrayBoxNum($params['data']['number'], $params['data']['packing_id']);
            $params['data']['tray_number'] = $trayBoxNum['tray_num'];
            $params['data']['box_number'] = $trayBoxNum['box_num'];
            $params['data']['specification'] = $specification['packing_num'] . ' / ' . $specification['unit_name'] . " /" . $specification['layup_num'];
            $this->warehousingSonModel->findBy($params['data']['id'], ['pallet_no']);
            $res = $this->warehousingSonModel->where('pallet_no', $params['data']['pallet_no'])->where('id', '<>', $params['data']['id'])->find();
            if (!empty($res)) {
                return CatchResponse::fail('栈板号:' . $params['data']['pallet_no'] . '，已经存在!');
            }
            return CatchResponse::success($this->warehousingSonModel->updateBy($params['data']['id'], $params['data']));
        }
    }

    /**
     * 入库商品明细编辑
     * @time 2022/01/19 11:52
     * @param $id
     * @param Request $request
     * @return Response
     */
//    public function update(Request $request) : Response
//    {
//        $params = $request->filterEmptyField()->post();
//        $params['type'] = 'edit';
//        $params['id'] = $params['id'];
//        $params = $this->goods_info($params);
//        if($params['code'] === 0){
//            return CatchResponse::fail($params['msg']);
//        }else{
//            $specification=Db::table('db_packing')->field('packing_num,unit_name')->where('packing_id',$params['data']['packing_id'])->find();
//            $params['data']['specification']=$specification['packing_num'].' / '.$specification['unit_name'];
//            return CatchResponse::success($this->warehousingSonModel->updateBy($params['data']['id'], $params['data']));
//        }
//    }

    /**
     * 商品信息
     * @return array
     */
    public function goods_info($params)
    {
        //入库数量对比
        $where1['warehousing_id'] = $params['warehousing_id'];
        $where1['deleted_at'] = 0;
        $goods_number = DB::name('db_warehousing')->where($where1)->value('goods_number');
        if ($params['type'] === 'edit') {
            $where[] = ['id', '<>', $params['id']];
        }

        $where[] = ['warehousing_id', '=', $params['warehousing_id']];
        $where[] = ['deleted_at', '=', 0];

        $number = Db::name('db_warehousing_son')->field('SUM(number) as number')->where($where)->find();

        $number1 = intval($number['number']) + intval($params['number']);

        if ($number1 > $goods_number) {
            return array('code' => 0, 'msg' => '商品数量大于商品总数量，请核对商品数量');
        }

        //商品
        $where2['goods_id'] = $params['goods_id'];
        $where2['deleted_at'] = 0;
        $info = DB::name('db_product')
            ->field('barcode,goods_name,goods_Ename,goods_Cname,supplier_id,manufacturer_id,HSCODE')
            ->where($where2)
            ->find();

        $params['HSCODE'] = $info['HSCODE'];
        $params['goods_name'] = $info['goods_name'];
        $params['goods_Ename'] = $info['goods_Ename'];
        $params['goods_Cname'] = $info['goods_Cname'];
        $params['supplier_id'] = $info['supplier_id'];
        $params['manufacturer_id'] = $info['manufacturer_id'];
        $where3['supplier_id'] = $info['supplier_id'];
        $where3['deleted_at'] = 0;
        $params['supplier_name'] = DB::name('db_supplier')->where($where3)->value('supplier_name');
        $where4['manufacturer_id'] = $info['manufacturer_id'];
        $where4['deleted_at'] = 0;
        $params['manufacturer_name'] = DB::name('db_manufacturer')->where($where4)->value('manufacturer_name');

        //包装
        $where5['packing_id'] = $params['packing_id'];
        $where5['deleted_at'] = 0;
        $packing = DB::name('db_packing')
            ->field('packing_id,packing_num,unit_name')
            ->where($where5)
            ->find();

        $params['p_barcode'] = $packing['packing_id'];
        $params['packing_num'] = $packing['packing_num'];
        $params['unit_name'] = $packing['unit_name'];

        unset($params['type']);
        return array('code' => 1, 'msg' => '', 'data' => $params);
    }

    /**
     * 入库商品明细删除
     * @time 2022/01/19 11:52
     * @param $id
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request): Response
    {
        $id = $request->post('id');
        $warehousing_son_id = Db::table('db_warehousing_son')->where('id', $id)->value('warehousing_son_id');
        Db::table('db_tray')->where('warehousing_son_id', $warehousing_son_id)->delete();
        return CatchResponse::success($this->warehousingSonModel->deleteBy($id));
    }

    /**
     * 商品总数量剩余数
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function goodsNumber(Request $request): Response
    {
        $warehousing_id = $request->post('warehousing_id');
        if (empty($warehousing_id)) {
            return CatchResponse::fail('缺少必要参数');
        }
        $where = [];
        $where[] = ['deleted_at', '=', 0];
        $where[] = ['warehousing_id', '=', $warehousing_id];
        $goods_number = DB::name('db_warehousing')->where($where)->field('goods_number')->find();
        $map = [];
        $map[] = ['warehousing_id', 'in', $warehousing_id];
        $map[] = ['deleted_at', '=', 0];
        $number = Db::name('db_warehousing_son')->field('SUM(number) as number')->where($map)->find();

        $data['number'] = intval($goods_number['goods_number']) - intval($number['number']);

        return CatchResponse::success($data);
    }

    /**
     * 打印
     * @time 2022/01/19 11:52
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function print(Request $request)
    {
        $data = $request->post();
        //主单信息
        $where['warehousing_id'] = $data['warehousing_id'];
        $warehousing = DB::name('db_warehousing')
            ->where($where)
            ->field('warehousing_id,project_id,project_client,settlement,goods_number,customer_business_number,actual_number,customer_order_type,created_at,tenant_id')
            ->find();
        $warehousing['created_at'] = date('Y-m-d H:i:s', $warehousing['created_at']);
        $warehousing['username'] = DB::name('users')->where('id', $warehousing['tenant_id'])->value('username');

        //项目
        $warehousing['project_id_name'] = DB::name('db_project')->where('project_id', $warehousing['project_id'])->value('project_name');
        //项目和委托人
        $warehousing['project_client_name'] = DB::name('db_project')->where('project_id', $warehousing['project_client'])->value('project_name');

        //商品信息
        $where1['warehousing_son_id'] = $data['warehousing_son_id'];
        $warehousing_son = DB::name('db_warehousing_son')
            ->where($where1)
            ->field('id,warehousing_son_id,goods_id,HSCODE,goods_name,supplier_name,packing_num,unit_name,batch_number,number,box_number,tray_number,actual_number')
            ->find();

        //托盘
        $where3['t.status'] = 1;
        $where3['t.warehousing_id'] = $data['warehousing_id'];
        $where3['t.warehousing_son_id'] = $data['warehousing_son_id'];
        $tray = DB::name('db_tray')->alias('t')
            ->join('db_warehouse_config w', 'w.config_id = t.config_id')
            ->where($where3)
            ->field('t.id,t.warehousing_son_id,t.tray_id,w.name,t.number,t.box_number,t.goods_status')
            ->select()
            ->toArray();
        $warehousing_son['tray_son'] = $tray;
        $warehousing['son'] = $warehousing_son;
        return CatchResponse::success($warehousing, '查询成功');
    }

    //项目选择库位（三种状态）
    public function projectWarehouseConfig($id)
    {
        $warehouse_project_client = Db::table('db_warehousing')->where('warehousing_id', $id)->value('project_client');
        $project_id = Db::table('db_project')->where('project_id', $warehouse_project_client)->value('id');

        $list = (new WarehouseConfig)->getProjectLevel3Status($project_id);

        $tree = (new WarehouseConfig)->getProjectLevel2Tree($list);

        return CatchResponse::success($tree, '查询成功');
    }

    //明细单-指定库位-第三层级
    public function getConfigLevel3($id)
    {
        $warehousing_son_config_attribute = $this->warehousingSonModel->find($id);
        $type = $warehousing_son_config_attribute->warehousing_son_config_attribute;
        $config_attribute_arr = explode(',', $type);

        $result = (new WarehouseConfig)->where([
            'usage' => $config_attribute_arr[0],
            'parent_id' => $config_attribute_arr[1],
            'isstatus' => 1
        ])
            ->select()->toArray();

        return CatchResponse::success($result, '查询成功');
    }
}